  <template>
    <div>
      <el-dialog title="新增人力需求" :visible.sync="isShow" @close="closeDialog" :close-on-click-modal="false" width="95%"
        @open="openDialog">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="small">
          <el-row :gutter="10">
            <!-- <el-col :span="13">
              <el-form-item label="机构名称" prop="branchNO">
                <el-popover placement="bottom" width="200" trigger="click" v-model="popoverShow">
                  <el-tree :data="option.treedata" :highlight-current="true" :expand-on-click-node="false"
                    default-expand-all :props="defaultProps" @node-click="handleNodeClick">
                  </el-tree>
                  <el-input slot="reference" size="small" v-model="ruleForm.branchName" placeholder="请选择机构"></el-input>
                </el-popover>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="人力名称" prop="name">
                <el-input v-model="ruleForm.name" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技能" prop="SKILLFLG">
                <el-select size="small" v-model="ruleForm.SKILLFLG" clearable placeholder="请选择技能">
                  <el-option
                    v-for="item in SKILLFLGS"
                    :key="item.FIELDKEY"
                    :label="item.FIELDVALUE"
                    :value="item.FIELDKEY">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
             <el-col :span="16">
              <el-form-item label="导入人力">
                <div class="">
                  <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构名称" prop="branchNO">
                <select-tree  size="small"  :branch="ruleForm.branchName" @getBranchName="getBranch"></select-tree>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="说明"prop="desc">
                <el-input type="textarea" size="small" :rows="2" v-model="ruleForm.desc"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <p>
                <i class="header-icon el-icon-s-tools"></i>&nbsp;&nbsp;人力需求表
              </p>
              <!-- <el-collapse v-model="activeName">
                <el-collapse-item name="1"> 
                  <template slot="title">
                    <i class="header-icon el-icon-s-tools"></i>&nbsp;&nbsp;人力需求表
                  </template>-->
                  <!-- <el-col :span="5">
                    <el-select v-model="ruleForm.branchName" placeholder="请选择机构" @change="testChange" style="width:100%"
                      size="small">
                      <el-option v-for="(item,index) in testData" :key="index" :label="item.branchName"
                        :value="item.branchNO">
                      </el-option>
                    </el-select>
                  </el-col> -->
                  <el-col :span="22" >
                    <el-button @click="resetDateFilter" type="primary" size="small" icon="el-icon-refresh">清除日期过滤器
                    </el-button>
                    <el-button type="primary" :disabled="tableData.length == 0" size="small" icon="el-icon-download"
                      @click="handleExcelToJson">
                      批量导出</el-button>
                  </el-col>
                  <el-col :span="24" style="margin-top:20px;height:400px;overflow:auto;">
                    <el-table :data="tableData" style="width: 100%;" ref="filterTable">
                      <el-table-column prop="FDATE" label="日期" column-key="FDATE" sortable
                        :filter-method="filterHandler" :filters="dateOption">
                      </el-table-column>
                      <el-table-column prop="FTIME" label="时间">
                      </el-table-column>
                      <el-table-column prop="MANCOUNT" label="人力">
                      </el-table-column>
                    </el-table>
                  </el-col>
            </el-col>
            <el-col :span="16">
              <p>
                <i class="header-icon el-icon-data-line"></i>&nbsp;&nbsp;人力需求图
              </p>
                <!-- </el-collapse-item>
                <el-collapse-item name="2"> -->
                  <!-- <template slot="title">
                  </template> -->
                  <el-col :span="24">
                    <!--为echarts准备一个具备大小的容器myChart-->
                    <div id="main" style="width: 100%;height: 400px;"></div>
                  </el-col>
                <!-- </el-collapse-item>
              </el-collapse> -->
            </el-col>
            <el-col :span="5" :offset="19" style="margin-top:10px;">
              <el-button type="primary" size="small" @click="submitForm('ruleForm')">保存</el-button>
              <el-button size="small" @click="resetForm('ruleForm')">取消</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </template>
  <script>
    import request from "@/common/utils/requestWFM";
    import Add from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEAdd'
    import echarts from 'echarts'
    import UploadExcelComponent from '@/components/UploadExcel/index'
    import bQuery from '@/message/wfm/baseData/branchManage/branchQuery'
    import branchQuery from '@/message/wfm/scheduleDataManage/branchData/branchDataQuery';
    import selectTree from "@/components/selectTree5/";
    export default {
      props: {
        option: Object
      },
      computed: {
        isShow: {
          get() {
            return this.option.isShow;
          },
          set(value) {
            this.option.isShow = value;
          }
        }
      },
      watch: {
        data: {
          handler(val) {
            this.drawTable()
          },
          deep: true
        },
        maxNum(val) {
          // console.log(val)
        }
      },
      components: {
        UploadExcelComponent,
        selectTree
      },
      data() {
        return {
          maxNum: 0,
          results: [], // 导入表格的数据
          dateOption: [],
          changeData: '',
          defaultProps: {
            children: 'children',
            label: 'BRANCHNAME'
          },
          popoverShow: false,
          activeName: ['1', '2'],
          ruleForm: {
            name: '',
            desc: '',
            branchNO: '',
            branchName: '',
            SKILLFLG: '',
          },
          rules: {
            name: [{
                required: true,
                message: '请输入人力名称',
                trigger: 'blur'
              },
              {
                min: 1,
                max: 10,
                message: '长度在 1 到 10 个字符',
                trigger: 'blur'
              }
            ],
            branchNO: [{
              required: true,
              message: '请选择机构名称',
              trigger: 'change'
            }],
            SKILLFLG: [{
                required: true,
                message: '请选择技能',
                trigger: 'blur'
            }],
          },
          testData: [],
          tableData: [],
          tableData1: [],
          tableHeader: [],
          that: '',
          myChart: '',
          // position: '',
          symbolSize: 10,
          charts: '',
          xData: [],
          data: [],
          SKILLFLGS: [] ,
        }
      },
      methods: {
        getBranch(data){
          this.ruleForm.branchNO = data.BRANCHNO
          this.ruleForm.branchName= data.BRANCHNAME
        },
        // 清除日期过滤
        resetDateFilter() {
          this.$refs.filterTable.clearFilter('FDATE');
        },
        filterHandler(value, row, column) {
          const property = column['property'];
          return row[property] === value;
        },
        async testChange(data) {
          this.ruleForm.branchNO = data
          this.queryBranch(data).then(value => this.ruleForm.branchName = value)
          let resBody = new branchQuery()
          resBody.data.BRANCHNO = this.ruleForm.branchNO+''
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            this.maxNum = response.BODY.RSPSTRUCT[0].AGENTNUM
            //console.log('hhhhhhhh',this.maxNum)
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                .ReturnMessage
            })
          }
          let arr = []
          this.data = []
          this.xData = []
          this.results.forEach((item, index) => {
            // item['日期'] = this.formatDate(item['日期'], '-')
            // item['时间'] = this.formatTime(item['时间'])
            if (item['机构号'] == this.ruleForm.branchNO) {
              this.xData.push(item['日期'] + ' ' + item['时间'])
              arr.push(item['FTE 要求'])
            }
          });
          let arr1 = []
          arr = arr.join(',').split(',')
          arr.forEach((item, index) => {
            item = item.split(',')
            item.unshift(index)
            arr1.push(item)
          });
          this.data = arr1
          this.drawLine('main')
          // this.test()
          this.test1()
          this.drawTable()
          window.addEventListener('resize', this.test1());
          this.myChart.on('dataZoom', this.updatePosition);
        },
        // 查询机构
        async queryBranch(branchNO) {
          let resBody = new bQuery()
          resBody.data.BRANCHNO = branchNO
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            return response.BODY.BRANCHDATA[0].BRANCHNAME
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        },
        // 查询机构的人数
        async queryBranchNum(branchNO) {
          let resBody = new branchQuery()
          resBody.data.BRANCHNO = branchNO+''
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            return response.BODY.RSPSTRUCT[0].AGENTNUM
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        },
        handleNodeClick(data) {
          this.ruleForm.branchName = data.BRANCHNAME
          this.ruleForm.branchNO = data.BRANCHNO
          this.popoverShow = false
        },
        handleExcelToJson() {
          this.filename = this.ruleForm.FTENAME + '人力需求'
          import('@/common/utils/Export2Excel').then(excel => {
            const tHeader = ['日期', '时间', 'FTE 要求']
            const filterVal = ['FDATE', 'FTIME', 'MANCOUNT']
            const list = this.tableData
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.downloadLoading = false
          })
        },
        formatJson(filterVal, jsonData) {
          // return jsonData.map(v => filterVal.map(j => {
          //   if (j === 'index') {
          //     return v[j] = i++
          //   } else {
          //     return v[j]
          //   }
          // }))
          return jsonData.map(v => filterVal.map(j => v[j]))
        },
        submitForm(formName) {
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              let resBody = new Add()
              resBody.data.BRANCHNO = this.ruleForm.branchNO
              resBody.data.FTENAME = this.ruleForm.name
              resBody.data.NOTES = this.ruleForm.desc
              resBody.data.SKILLFLG = this.ruleForm.SKILLFLG
              this.tableData.forEach(item => {
                item.FDATE = item.FDATE.split('-').join('');
              });
              resBody.data.FTE = this.tableData
              let response = await request(resBody);
              if (response.SYS_HEAD.ReturnCode == "000000") {
                this.option.isShow = false
                this.$emit("ListenFTE")
              } else {
                this.$message({
                  type: "error",
                  message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                    .ReturnMessage
                })
              }
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        closeDialog() {
          if (this.$refs['ruleForm'] != undefined) {
            this.$refs['ruleForm'].clearValidate();
            this.$refs['ruleForm'].resetFields();
            this.ruleForm.branchName = ''
            this.ruleForm.branchNO = ''
            this.dateOption = []
            this.tableData = []
            this.testData = []
            this.xData = [],
            this.data = []
          }
          this.resetDateFilter()
        },
        resetForm(formName) {
          this.$refs[formName].clearValidate();
          this.$refs[formName].resetFields();
          this.isShow = false
        },
        formatDate(numb, format) {
          const time = new Date((numb-1) * 24 * 3600000 + 1)
          time.setYear(time.getFullYear() - 70)
          const year = time.getFullYear() + ''
          const month = time.getMonth() + 1 + ''
          const date = time.getDate() -1 + ''
          if (format && format.length === 1) {
            return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
          }
          return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
        },
        formatTime(val) {
          let secs = (val * 24 * 60 * 60).toFixed(0)
          if (secs && parseInt(secs.toString())) {
            var second = parseFloat((secs % 60).toFixed(1));
            var minute = Math.floor(secs / 60);
            var hour = Math.floor(secs / 3600);
            hour = this.formatNumber(Math.floor(minute / 60));
            minute = this.formatNumber(minute % 60);
            second = this.formatNumber(second);
            return hour + ':' + minute
          } else {
            return '00:00'
          }
        },
        formatNumber(num) {
          return num < 10 ? '0' + num : num;
        },
        openDialog() {
          if (this.$refs['ruleForm'] != undefined) {
            this.$refs['ruleForm'].clearValidate();
            this.$refs['ruleForm'].resetFields();
            this.ruleForm.branchName = ''
            this.ruleForm.branchNO = ''
          }
          this.dateOption = []
          this.tableData = []
          this.testData = []
          this.xData = [],
          this.data = []
          this.$nextTick(() => {
            this.drawLine('main')
            // this.test()
            this.test1()
            this.drawTable()
            window.addEventListener('resize', this.test1());
            this.myChart.on('dataZoom', this.updatePosition);
          })
          this.SKILLFLGS = this.option.SKILLFLGS;
        },
        beforeUpload(file) {
          const isLt3M = file.size / 1024 / 1024 < 3
          if (isLt3M) {
            return true
          }
          this.$message({
            message: 'Please do not upload files larger than 3m in size.',
            type: 'warning'
          })
          return false
        },
        handleSuccess({
          results,
          header
        }) {
          console.log('222222222',results)
          let arr = []
          const obj = {}
          let branchName = ''
           // 去不同的日期 判断日期是否为7天或者31天，如果不是则重新导入
           const dateObjArr = results.reduce((prev, curr) => {
            obj[curr['日期']] ? true : obj[curr['日期']] = true && prev.push({
              date: curr['日期']
            });
            return prev
          }, [])
          console.log('33333',results)
          console.log('日期',dateObjArr)
          if(dateObjArr.length != 7 && dateObjArr.length != 31){
            this.$message({
                type: 'error',
                message: '人力需求数据必须为7天或者31天，请重新导入！'
              })
            return false
          }
          this.results = results
          
          // 取到不同的机构号
          const newObjArr = results.reduce((prev, curr) => {
            obj[curr['机构号']] ? true : obj[curr['机构号']] = true && prev.push({
              branchNO: curr['机构号']+''
            });
            return prev
          }, [])
          newObjArr.forEach(item => {
            this.queryBranch(item.branchNO).then(value => item.branchName = value)
          });
          this.testData = newObjArr // 机构号
         
          results.forEach(async (item, index) => {
            if (index == 0) {
              // if (this.ruleForm.branchNO == '') {
              this.ruleForm.branchNO = item['机构号']+''
              this.queryBranch(item['机构号']+'').then(value => this.ruleForm.branchName = value)
              // this.queryBranchNum(item['机构号']).then(value => this.maxNum = value)
              // }
            }
            item['日期'] = this.formatDate(item['日期'], '-')
            item['时间'] = this.formatTime(item['时间'])
            // item['日期'] = this.formatDate(parseInt(item['时间']), '-')
            // item['时间'] = item['时间'] + ''
            // item['时间'] = this.formatTime('0.'+item['时间'].split('.')[1])
            // console.log(item['时间'])
            if (item['机构号']+'' == this.ruleForm.branchNO) {
              this.xData.push(item['日期'] + ' ' + item['时间'])
              arr.push(item['FTE 要求'])
            }
          });
          this.$nextTick(async () => {
            // 取y轴最大值
            let resBody = new branchQuery()
            resBody.data.BRANCHNO = this.ruleForm.branchNO+''
            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              this.maxNum = response.BODY.RSPSTRUCT[0].AGENTNUM
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                  .ReturnMessage
              })
            }
            let arr1 = []
            arr = arr.join(',').split(',')
            arr.forEach((item, index) => {
              item = item.split(',')
              item.unshift(index)
              arr1.push(item)
            });
            this.data = arr1
            this.drawLine('main')
            // this.test()
            this.test1()
            this.drawTable()
            window.addEventListener('resize', this.test1());
            this.myChart.on('dataZoom', this.updatePosition);
          })
        },
        drawTable() {
          this.tableData = []
          this.dateOption = []
          if (this.xData.length == 0) {
            return false
          }
          this.tableData = this.data.map((val, index) => {
            return {
              'FDATE': this.xData[index].split(' ')[0],
              'FTIME': this.xData[index].split(' ')[1],
              'MANCOUNT': val[1]
            }
          })
          const obj = {}
          const newObjArr = this.tableData.reduce((prev, curr) => {
            obj[curr.FDATE] ? true : obj[curr.FDATE] = true && prev.push({
              text: curr.FDATE,
              value: curr.FDATE
            });
            return prev
          }, [])
          this.dateOption = newObjArr
        },
        drawLine() {
          this.data = this.data.map(function (val) {
            // console.log('纵坐标',val[1])
            return [val[0], Math.round(val[1])]
          })          
          this.myChart = echarts.init(document.getElementById('main'))
          this.myChart.setOption({
            title: {
              text: '人力需求折线图'
            },
            tooltip: {
              triggerOn: 'none',
              formatter: (params) => {
                return '时间: ' + this.xData[params.data[0]] + '<br>人力: ' + Math.round(params.data[1]);
              }
            },
            // grid: {
            //   left: 50,
            //   top: 40
            // },
            xAxis: {
              // min: 0,
              // max: 23,
              type: 'category',
              boundaryGap: false,
              // axisLabel: {
              //   formatter: function (value, index) {
              //     return parseInt(value)
              //   }
              // },
              data: this.xData,
              axisLine: {
                onZero: false
              }
            },
            yAxis: {
              min: 0,
              // max: 21,
              max: this.maxNum,
              type: 'value',
              axisLabel: {
                formatter: function (value, index) {
                  return parseInt(value)
                }
              },
              axisLine: {
                onZero: false
              }
            },
            dataZoom: [{
                type: 'slider',
                xAxisIndex: 0,
                filterMode: 'empty'
              },
              {
                type: 'inside',
                xAxisIndex: 0,
                filterMode: 'empty'
              },
            ],
            series: [{
              id: 'a',
              type: 'line',
              smooth: true,
              symbolSize: this.symbolSize,
              data: this.data,
              hoverAnimation: false
            }],

          })
        },
        showTooltip(dataIndex) {
          this.myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: dataIndex
          });
        },
        hideTooltip(dataIndex) {
          this.myChart.dispatchAction({
            type: 'hideTip'
          });
        },
        test2() {
          this.drawLine()
          this.test1()
        },
        test1() {
          this.myChart.setOption({
            graphic: echarts.util.map(this.data, (dataItem, dataIndex) => {
              const that = this // 因为ondrag函数必须在回调内使用this.position获取实时坐标，此处必须用that替换this
              return {
                // 'circle' 表示这个 graphic element 的类型是圆点。
                type: 'circle',
                shape: {
                  cx: 0,
                  cy: 0,
                  // 圆点的半径。
                  r: this.symbolSize / 2
                },
                // 用 transform 的方式对圆点进行定位。position: [x, y] 表示将圆点平移到 [x, y] 位置。
                // 这里使用了 convertToPixel 这个 API 来得到每个圆点的位置
                position: this.myChart.convertToPixel('grid', dataItem),
                // 这个属性让圆点不可见（但是不影响他响应鼠标事件）。
                invisible: true,
                // 这个属性让圆点可以被拖拽。
                draggable: true,
                // 把 z 值设得比较大，表示这个圆点在最上方，能覆盖住已有的折线图的圆点。
                z: 100,
                ondrag: echarts.util.curry(function (dataIndex) { // 此处必须用匿名函数，不能用箭头函数，否则拿不到拖动的坐标
                  let origin = that.myChart.convertToPixel('grid', that.data[dataIndex]) // 得到每个圆点原始位置
                  // let maxY = that.myChart.convertToPixel('grid', [40, 36]) // 最高温度为36摄氏度，暂未做封装
                  // 超过最高温度36将不能拖动,写死的最低点高度为240，最高点为40
                  // console.log('position',this.position[1])
                  this.position[1] = Math.round(this.position[1])
                  if (this.position[1] > 340) {
                    this.position[1] = 340
                  } else if (this.position[1] <= 60) {
                    this.position[1] = 60
                  }
                  // console.log(this.position[1])
                  this.position[0] = origin[0] // 控制每个点位只能在y轴方向移动
                  // this.position[1] = origin[1] // 控制每个点位只能在x轴方向移动
                  // 实时获取拖动的点位信息并根据此信息重新画图
                  that.data[dataIndex] = that.myChart.convertFromPixel('grid', this.position)
                  that.myChart.setOption({
                    series: [{
                      id: 'a',
                      // data: that.data.map(function(val){
                      //   return [Math.round(val[0]), Math.round(val[1])]
                      // }),
                      data: that.data,
                      type: 'line',
                      smooth: true,
                      hoverAnimation: false,                        
                    }]
                  })
                  // that.data = that.data.map(function (val) {
                  //   // console.log('纵坐标',val[1])
                  //   return [val[0], Math.round(val[1])]
                  // })
                  // console.log(that.data)
                }, dataIndex),
                onmousemove: echarts.util.curry(this.showTooltip, dataIndex),
                onmouseout: echarts.util.curry(this.hideTooltip, dataIndex),
                onmouseup: echarts.util.curry(this.test2)
              }
            })
          })

          //  on(window, 'resize', this.myChart.setOption({
          //   graphic: echarts.util.map(this.data, (item, dataIndex) => {
          //   return {
          //    position: this.myChart.convertToPixel('grid', item)
          //   }
          //   })
          //    }))
        },
        updatePosition() {
          // 节流
          if(!this.timeout) {
            this.timeout = setTimeout(() => {
              this.myChart.setOption({
                graphic: echarts.util.map(this.data, (item, dataIndex) => {
                  return {
                    position: this.myChart.convertToPixel('grid', item)
                  };
                })
              });
              clearTimeout(this.timeout);
              this.timeout = null;
            }, 2000);
          }
        }
      },
      //调用
      mounted() {
        // this.$nextTick(()=>{
        //   this.drawLine('main')
        //   // this.test()
        //   this.test1()
        //   this.drawTable()
        //   window.addEventListener('resize', this.test1());
        //   this.myChart.on('dataZoom', this.updatePosition);
        // })
      }
    }

  </script>
  <style lang="scss" scoped>
    /* * {
      margin: 0;
      padding: 0;
      list-style: none;
    } */

  </style>
